package liudan.archetype;

import com.mongodb.*;
import com.mongodb.util.JSON;

import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;

/**
 * Description:
 * Email: liudan@ucfgroup.com
 * Title
 * Copyright: Copyright (c) 2017
 * User: liudan
 * Created on 2017/4/5 10:26
 */
public class MongoDB {
    public static void main(String[] args) throws UnknownHostException {
        Mongo mongo = new Mongo("127.0.0.1:27017");

        List<String> dataList = mongo.getDatabaseNames();
        System.out.println(mongo.getDatabaseNames());
        System.out.println(dataList.size());
        for(String data:dataList){
            System.out.println("dbName;"+ data);
        }
        DB dbs = mongo.getDB("foobar");

        Set<String> collections = dbs.getCollectionNames();
        System.out.println("collections:"+ collections.size());
        for (String coll:collections){
            System.out.println(coll);
        }
    //获取一个集合persons
        DBCollection dbCollection = dbs.getCollection("persons");
        long count= dbCollection.getCount();
        System.out.println(count);

        DBCursor dbCursor = dbCollection.find();
        while(dbCursor.hasNext()){
            DBObject dbObject = dbCursor.next();
            //转换json
            System.out.println(JSON.serialize(dbObject));

            System.out.println("name:"+dbObject.get("name")+",email:"+ dbObject.get("email"));
        }
    }
}
